-- UIGroupPurChase
-- Create by huanghr
-- 团购界面

require "game/ui/form/group_buy/UIGroupBuyInfo"

-- UIGroupPurChase继承自Layer
UIGroupPurChase = class("UIGroupPurChase", function()
    return cc.Layer:create();
end);

function UIGroupPurChase.create()
    return UIGroupPurChase.new();
end

-- 最大行数
local MAX_GRID_ROW    = 2;
local MIN_GRID_COLUMN = 3;

-- 内部函数声明

-- 构造函数
function UIGroupPurChase:ctor()
    -- 初始化
    self:setName("UIGroupPurChase");
    local node = cc.CSLoader:createNode("layout/market/GroupPurchase.csb");
    self:addChild(node);
    self.node = node;

    --self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    local CT = node:getChildByName("CT");
    local scrollview = findChildByName(CT, "template/scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 水平滑动，需要显示左右蒙版
    local mask3 = findChildByName(self.CT, "template/mask3");
    mask3:setVisible(true);
    local mask4 = findChildByName(self.CT, "template/mask4");
    mask4:setVisible(true);

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(2);

    self.scrollview = findChildByName(self.node, "TOP/scrollview")

    -- 获得未销售的冈布奥
    -- self.list = MarketM.getSellGoldsByType("hero");
    self.list = ME.user:getAllPetIds();

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化格子
    self:initGrids(self.node);

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIGroupPurChase:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- TOP顶部居中并缩放至合适大小
    AlignM.alignToTopCenter(node, "TOP");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 初始化格子
function UIGroupPurChase:initGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 23;

    -- 图标间距(纵向)
    local hGap = 33;

    -- 图标宽度
    local iconWidth = 128;

    -- 图片高度
    local iconHeight = 163;

    local topHGap  = 100;
    local leftWGap = 20;

    -- 获取团购的冈布奥的信息
    local goodsList = GroupPurchaseM.getGoodIsds();

    -- 总数
    local totalCount = #goodsList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/market/GroupPuechaseItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsHorizontal(self, self.scrollView, itemNode, totalCount, MAX_GRID_ROW, MIN_GRID_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, leftWGap, self.registerItemTouchEvent);
end

-- 显示英雄选择界面
function UIGroupPurChase:redraw()
    -- 显示标题
    local titleLabel = findChildByName(self.CT, "template/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(getLocStr("group_buy_bonus"));

    --  显示标题2
    local titleLabel2 = findChildByName(self.CT, "template/subhead");
    TextStyleM.setSubheadStyle(titleLabel2)
    titleLabel2:setString(getLocStr("buy_pets_gain_bonus"));

    -- 设置充值按钮的文本样式
    local btnBuyGem = findChildByName(self.node, "BT/btn_buy_gem");
    TextStyleM.setTextStyle(btnBuyGem, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBuyGem:setTitleText(getLocStr("recharge"));

    -- 获取团购的冈布奥的信息
    local goodsList = GroupPurchaseM.getGoodIsds();

    local heroList = {};
    -- 收集冈布奥的信息
    for _, goodsId in pairs(goodsList) do
          local info = MarketM.getGoodsInfo(goodsId);
          table.insert(heroList, info);
    end

    local totalGridCount = #heroList;

    if not heroList or #heroList == 0 then
        cclog("收集英雄信息失败。");
        return;
    end

    -- 显示信息
    for i = 1, totalGridCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initGridInfo(grid, heroList[i]);
        end
    end
end

-- 重绘英雄星级
function UIGroupPurChase:redrawHeroStar(starNode, classId)
    local hero = PetM.getMyPet(classId);
    if not hero then
        return;
    end

    -- 获取英雄阶位
    local starNum = hero:getRank();

    -- 生成星星层，直接挂到结点上
    local lightStarPath = "images/ui/symbol/star_little.png";
    --local darkStarPath  = "images/ui/symbol/star_little2.png";
    local layer = createStarLayer(starNum, lightStarPath, "center", -0.7);
    if not layer then
        return;
    end
    starNode:removeAllChildren();
    starNode:addChild(layer);
end

-- 初始化格子信息
function UIGroupPurChase:initGridInfo(grid, info)
    local heroId = info.bonus[1][2];

    -- 领奖的总次数
    local icon = findChildByName(grid, "icon");
    local starNode = findChildByName(grid, "star");

    local bg = findChildByName(grid, "bg");

    local timesLabel = findChildByName(grid, "times");

    -- 领奖标示
    local tipIcon = findChildByName(grid, "tip_icon");

    local totalCount = GroupPurchaseM.query(info.id, "max_times");

    -- 已经领取过的奖励等级
    local hasTook = GroupPurchaseM.hasTookLevel(info.id);

    -- 可领奖的次数
    local canTake = GroupPurchaseM.maxBonusLevel(info.id);

    -- 可领奖的次数
    local num = findChildByName(grid, "num");

    if canTake - hasTook < 1 then
        num:setVisible(false);
    else
        TextStyleM.setTextStyle(num, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    end
    num:setString(canTake - hasTook);

    -- 英雄头像
    local fileName = PetM.getDefaultIcon(heroId);
    local iconPath = getHeroIconPath(fileName);
    icon:loadTexture(iconPath);

    if table.indexOf(self.list, heroId) == -1 then
        -- 无法升阶时，背景置灰
        -- setGrayMode(icon, true);
        icon:setOpacity(175);
        setGrayMode(bg, true);

        TextStyleM.setTextStyle(timesLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_RED, true, -3);
        timesLabel:setString(getLocStr("not_buy"));
        timesLabel:setPosition(0, timesLabel:getPositionY())
        timesLabel:setAnchorPoint(0.5, 0.5);
        tipIcon:setVisible(false);
        -- 初始化星级
        num:setVisible(false);
        self:redrawHeroStar(starNode, heroId);
    else
        setGrayMode(icon, false);
        setGrayMode(bg, false);
        local str = hasTook.. "/" .. totalCount;
        TextStyleM.setTextStyle(timesLabel, TextStyleM.TEXT_SIZE_MINI, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2);
        timesLabel:setString(str);
        tipIcon:loadTexture("images/ui/market/baoxiang.png");
        -- 初始化星级
        self:redrawHeroStar(starNode, heroId);
    end
end

-- 注册商品点击事件
function UIGroupPurChase:registerItemTouchEvent(node)
   --
    local childBg = node:getChildByName("bg");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            if UIMgr:getCurrentScene():isOpen("UIGroupBuyInfo") then
                UIMgr:getCurrentScene():removeForm("UIGroupBuyInfo");
            end

            local goodsList = GroupPurchaseM.getGoodIsds();
            local id = goodsList[node.index];
            local uiGroupBuyInfo = UIGroupBuyInfo.create(id);
            UIMgr.getCurrentScene():addForm(uiGroupBuyInfo);
            AudioM.playFx("button_caption");
        end
    end
    childBg:addTouchEventListener(onBackClick);
end

-- 注册事件处理回调函数
function UIGroupPurChase:registerEventCallback()
    -- 注册团购信息更新的回调
    EventMgr.register("UIGroupPurChase", event.UPDATE_PURCHASE_PROGRESS, function()
          self:redraw();
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIGroupPurChase");

            -- 显示商城主界面
            -- 将背景隐藏
            if UIMgr:getCurrentScene():isOpen("UIMarketMain") then
                local uiForm = UIMgr:getCurrentScene():getFormByName("UIMarketMain");
                uiForm:showMarket();
            end
        elseif eventType == "enter" then
            -- 将背景隐藏
            if UIMgr:getCurrentScene():isOpen("UIMarketMain") then
                local uiForm = UIMgr:getCurrentScene():getFormByName("UIMarketMain");
                uiForm:hideMarket();
            end
        end
    end);
end

-- 注册点击事件
function UIGroupPurChase:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName("UIGroupPurChase");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册内购按钮点事件
    local btnBuyGem = findChildByName(self.node, "BT/btn_buy_gem");
    local function onBuyGemClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 显示钻石购买界面
            local ct = findChildByName(self.node, "CT");
            ct:setVisible(false);
            local top = findChildByName(self.node, "TOP");
            top:setVisible(true);
            self:showRechargePage();

            -- 播放界面音效
           AudioM.playFx("market_buy_btn");

           btnBuyGem:setVisible(false);
       end
    end
    btnBuyGem:addTouchEventListener(onBuyGemClick);
end

-- 显示充值页面
function UIGroupPurChase:showRechargePage()
    local list = MarketM.getSellGoldsByType("recharge");

    local function initFunc(child, info)
        self:initRechargeItem(child, info)
    end
    self:showPage("sub", list, getLocStr("recharge"), initFunc, true);
end

-- 初始化充值页面项
function UIGroupPurChase:initRechargeItem(child, info)
    local bg = child:getChildByName("bg");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            bg:runAction(cc.ScaleTo:create(0.1, 0.97));
        elseif eventType == ccui.TouchEventType.canceled then
            bg:runAction(cc.ScaleTo:create(0.1, 1));
        elseif eventType == ccui.TouchEventType.ended then
            bg:runAction(cc.ScaleTo:create(0.1, 1));

            -- AudioM.playFx("button_click");
            -- 显示购买界面
            local goodsId = info.id;
            self:openBuyForm(goodsId, 2);
        end
    end
    bg:addTouchEventListener(onClick);

    -- 获取充值商品的价格
    local price;
    local goodsId = info.id;
    local sku = MarketM.querySku(goodsId);
    if type(sku) ~= 'string' then
        price = string.format("$%.2f", table.values(info["price"])[1]);
    else
        price = MarketM.getPriceBySku(sku);
    end

    local priceLabel = findChildByName(child, "bg/price");
    priceLabel:setVisible(true);
    TextStyleM.setTextStyle(priceLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_ORANGE, true);
    priceLabel:setString(price);
    priceLabel:setPositionY(priceLabel:getPositionY() + 20);
end

-- 显示商品页
function UIGroupPurChase:showPage(pageType, list, title, itemInitFunc, showEffect)
    local scrollview = self.scrollview;

    -- 先清空所有页面
    scrollview:removeAllChildren();

    -- 标记类型
    self.pageType = pageType;

    -- 设置标题文本
    local titleLabel = findChildByName(self.node, "TOP/title_node/title")
    titleLabel:setString(title);
    TextStyleM.setArtWordTitleStyle(titleLabel);

    local iconNode  = cc.CSLoader:createNode("layout/market/MarketItem.csb");
    local widget = replaceNodeWithWidget(iconNode);

    -- 左边距
    local leftMargin = 0;

    -- 行间距
    local gap = 10;
    local offset = 0;

    -- 单个表项高度
    local widgetHeight = 145;
    if pageType ~= "main" then
        widgetHeight = 110;
        gap = 0;

        offset = -3;
    end

    local totalNum = #list;
    self.totalNum = totalNum;

    local startHeight = 0;

    -- 计算总高度
    local totalHeight = totalNum * (widgetHeight + gap);
    if totalHeight < scrollview:getInnerContainerSize().height then
        startHeight = scrollview:getInnerContainerSize().height - totalHeight - 20;
    end

    startHeight = startHeight + offset;

    -- 设置内部滚动区域的高度
    scrollview:setInnerContainerSize(cc.size(scrollview:getInnerContainerSize().width,
        math.max(totalHeight, scrollview:getInnerContainerSize().height)));

    self.items = {};
    local i = 0;
    for j = #list, 1, -1 do
        local info = list[j];
        local child = widget:clone();
        local x = leftMargin;
        local y = startHeight + i * (widgetHeight + gap);
        child:setPositionX(x);
        child:setPositionY(y);

        -- 初始化奖励
        child:setTag(i);
        child.type = info.type;
        itemInitFunc(child, info);

        scrollview:addChild(child);
        i = i + 1;

        table.insert(self.items, child);
    end

    if showEffect then
        local list = {};
        for j = #self.items, 1, -1 do
            table.insert(list, self.items[j]);
        end

        commonScrollItemFlyIn(list);
    end
end

-- 显示购买界面
function UIGroupPurChase:openBuyForm(goodsId, priceType)
    local function callback()
        if MarketM.query(goodsId, "classify") == "hero" then
            -- 显示英雄界面
            UIMgr.getCurrentScene():removeFormByName("UIHeroDetailInfo");
            local uiBuyHero = UIHeroDetailInfo.create(MarketM.query(goodsId, "bonus")[1][2], "market", goodsId);
            UIMgr.getCurrentScene():addForm(uiBuyHero);
        else
            UIMgr.getCurrentScene():removeFormByName("UIBuyGoods");
            local uiBuyGoods = UIBuyGoods.create(goodsId, priceType);
            UIMgr.getCurrentScene():addForm(uiBuyGoods);
        end

        -- 播放界面音效
        AudioM.playFx("market_open_child");
    end
    checkIfGuestNeedBind(callback);
end